package com.herench.bunch.lab.entrance.impl;

import com.herench.bunch.commons.support.MessageBuilder;
import com.herench.bunch.commons.support.MessageProcessor;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.support.ResponseMessage;
import com.herench.bunch.commons.utils.MessageHelper;
import com.herench.bunch.lab.entrance.LabWebservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;


@Component("labWebservice")
@javax.jws.WebService(endpointInterface = "com.herench.bunch.lab.entrance.LabWebservice", serviceName = "labWebservice", targetNamespace = "http://entrance.lab.bunch.herench.com/")
public class LabWebserviceImpl implements LabWebservice {


    private static final Logger logger = LoggerFactory.getLogger(LabWebservice.class);

    @Autowired
    private MessageProcessor processor;

    @Override
    public String send(String originalMsg) {
        String responseMessage = null;
        try {
            logger.info("request:" + URLDecoder.decode(originalMsg, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ResponseMessage res = null;
        RequestMessage requestMessage = new RequestMessage(originalMsg);
        try {
            requestMessage = MessageHelper.decoration(requestMessage);
            res = processor.handler(requestMessage);
        } catch (Exception e) {
            res = MessageBuilder.builderErrResMsg(requestMessage, e.getMessage());
            logger.error("exception:" + e.getMessage());
            e.printStackTrace();
        }

        logger.info("response:" + res.getHl7Message());
        responseMessage =MessageHelper.encode( res.getHl7Message());
        return responseMessage;
    }

}
